import 'dart:io';

import 'package:dart_bean/cass_info.dart';
import 'package:dart_bean/util/ext.dart';

class DartSourceUpdater {
  final File file;
  bool _fileUpdated = false;
  final Map<CassInfo, String> _classUpdates = {};
  late String _fileContent = file.readAsStringSync();

  DartSourceUpdater(this.file);

  void updateClassContent(CassInfo clazz, ClassUpdaterFunction f) {
    final newContent = f(clazz, _classUpdates[clazz] ?? clazz.content);
    if (newContent != null) _classUpdates[clazz] = newContent;
  }

  void updateImport(ImportUpdaterFunction f) {
    final newFileContent = f(_fileContent);
    if (newFileContent != null) {
      _fileContent = newFileContent;
      _fileUpdated = true;
    }
  }

  void _commitClassUpdates() {
    _classUpdates.forEach((clazz, newContent) {
      _fileContent = _fileContent.replaceFirst(clazz.content, newContent);
    });
  }

  void commitUpdates() {
    _commitClassUpdates();
    if (_classUpdates.isNotEmpty || _fileUpdated) file.writeAsStringSync(safeDartFormatter(_fileContent));
  }
}

///return newClassContent or null, if no updates
typedef ClassUpdaterFunction = String? Function(CassInfo clazz, String classContent);

///return newFileContent or null, if no updates
typedef ImportUpdaterFunction = String? Function(String fileContent);
